<template>
  <div>
    <Breadcrumb :title="subTitle " :opt-data="commandOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="commandData"
          :custom-empty="true"
          @pageChanged="genProtocolCommandData"
          @sizeChanged="genProtocolCommandData"
          @filterChange="genProtocolCommandData">
          <EmptyContent slot="empty" :opt-data="commandOptData"></EmptyContent>
        </EZTable>
      </div>
      <!--关联通用命令-->
      <el-dialog title="关联通用命令" :visible.sync="showCommandDialog" width="600px"  :close-on-click-modal="false" center>
        <el-form :ref="protocolCommandFormRef" :model="protocolCommandForm" :rules="protocolCommandFormRules"
                 size="small" label-width="130px">
          <el-form-item label="通用命令" prop="generalCommands">
            <el-select v-model="protocolCommandForm.generalCommands" clearable filterable multiple collapse-tags
                       class="width-100"
                       placeholder="请选择通用命令"
                       @change="genCommChanged">
              <el-option-group v-for="(group, idx) in genCommData" :key="idx" :label="group.label">
                <el-option v-for="(item, idx) in group.options" :key="idx"
                           :label="`${item.methodName} ${item.methodAlias || ''}`" :value="item._id">
                  <span>{{item.methodName}}</span>
                  <span class="mar-lft font-color-warning">{{item.methodAlias || ''}}</span>
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="showCommandDialog = false">取消</el-button>
              <el-button size="medium" type="primary" @click="protocolCommandFormSubmit">提交</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>

  </div>
</template>
<script>
  import EZTable from "@/components/table/EZTable.vue";
  import {routerMeta} from "@/router/routerMeta";
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {confirmHandle, deepCopyWithJson, messageHandle} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import generalProtocolCommand from "@/config/table/generalProtocolCommand";
  import {msgCode} from "@/config/string";
  import {commonConfig} from "@/config/common";

  export default {
    name: "GeneralProtocolCommand",
    components: {EZTable},
    data() {
      return {
        protocolId: '',
        protocolInfo: {},
        tableLoading: true,
        tableId: tableIdConfig.generalProtocolCommand,
        tableHdl: null,
        commandData: [],
        historyRelationId: '',
        historyTitle: '',
        historyDialog: false,
        subTitle: '',
        showCommandDialog: false,
        protocolCommandFormRef: 'protocolCommandFormRef',
        protocolCommandForm: {},
        protocolCommandFormRules: {
          generalCommands: [
            {required: true, message: '请关联通用命令', trigger: 'blur'}
          ],
        },
        genCommData: [],
        deviceType: '',
        action: 'add'
      }
    },

    computed: {
      commandOptData() {
        return [
          {
            type: 'btn',
            label: '新增命令',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          },
          {
            type: 'btn',
            label: '关联命令',
            icon: 'icon-salescenter',
            callback: () => {
              this.relateCommandBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.subTitle = this.$route.query.subTitle;
      this.protocolId = this.$route.params.pid;
      this.deviceType = this.$route.query.deviceType;
      this.initTableConfig();
      this.getProtocolInfo();
      this.genProtocolCommandData();
      this.getGenCommData();
      this.initProtocolCommandForm()
    },
    methods: {
      initProtocolCommandForm() {
        this.protocolCommandForm = {
          protocolId: this.protocolId,
          generalCommands: [],
          action: this.action,
        };
      },
      resetComponentForm() {
        this.initProtocolCommandForm();
        const protocolCommandForm = this.$refs[this.protocolCommandFormRules];
        protocolCommandForm && protocolCommandForm.resetFields();
      },
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, generalProtocolCommand);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const command = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.$router.push({
                name: routerMeta.generalProCommandEdit.name,
                params: {
                  gid: command._id
                },
                query: {protocolId: this.protocolId,}
              });
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteProtocolCommand(command);
              this.protocolCommandForm = {
                protocolId: this.protocolId,
                generalCommands: [command._id],
                action: 'del',
              };
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      getProtocolInfo() {
        const selector = {_id: this.protocolId};
        const tableParam = this.tableHdl.assembleTableParam();
        API.protocol.protocolList({selector, ...tableParam}).then(result => {
          const {data = {}} = result;
          this.protocolInfo = data;
          this.subTitle = data[0].protocolName
        }).catch(err => {
        });
      },
      genProtocolCommandData() {
        this.tableLoading = true;
        const selector = {generalProtocolId: this.protocolId};
        const tableParam = this.tableHdl.assembleTableParam();
        API.generalProtocol.generalProtocolCommandList({selector, ...tableParam}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          const assembleParamsText = (src = []) => {
            const destArray = [];
            // 前端数据展示渲染
            src.forEach(s => {
              const key = `key: <span class="font-color-success">${s.paramKey || '--'}</span>`;
              const alias = `, alias: <span class="font-color-success">${s.paramAlias || '--'}</span>`;
              const storeKey = s.storeKey ? `, storeKey: <span class="font-color-danger">${s.storeKey || '--'}</span>` : '';
              destArray.push(`<span>${key}${alias}${storeKey}</span>`);
            });
            return destArray.join('</br>');
          };
          this.commandData = data.map(d => {
            return {
              ...d,
              statusParamsText: assembleParamsText(d.statusParams),
              controlParamsText: assembleParamsText(d.controlParams),
            }
          });

          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      clickCreateBtn() {
        this.$router.push({
          name: routerMeta.generalProCommandAdd.name,
          query: {protocolId: this.protocolId, deviceType: this.deviceType}
        });
      },
      deleteProtocolCommand(command = {}) {
        confirmHandle({label: `确定要删除协议命令：${command.methodAlias} 吗?`}).then(() => {

          API.generalProtocol.generalProtocolCommandRelated(this.protocolCommandForm).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '协议命令'});
            this.tableHdl.judgeTableMatched();
            this.genProtocolCommandData();
          });
        }).catch(() => {
        });
      },
      relateCommandBtn() {
        this.resetComponentForm()
        this.action = 'add'
        this.showCommandDialog = true;

      },
      //拿通用命令数组
      getGenCommData() {
        const param = {deviceType: this.deviceType};
        API.genCommand.genCommAll(param).then(result => {
          const {data = []} = result;
          this.commandFormLoading = false;
          this.genCommData = [];
          // 将通用命令根据命令类型分组
          const initGenCommData = deepCopyWithJson(commonConfig.commandType).map(ct => {
            return {...ct, options: []};
          });
          data.forEach(d => {
            const genComm = initGenCommData.find(f => {
              return f.value === d.generalCommandType;
            });
            genComm && (genComm.options.push(d));
          });
          initGenCommData.forEach(gc => {
            const {options = []} = gc;
            options.length && (this.genCommData.push(gc));
          });
        }).catch(err => {
          console.log('err', err)
          this.commandFormLoading = false;
        });
      },
      genCommChanged() {
        let flatGenCommData = [];
        this.genCommData.forEach(gc => {
          flatGenCommData = _.union(flatGenCommData, gc.options || []);
        });
        // this.genCommInfo = flatGenCommData.find(fgc => {
        //   return fgc._id === this.commandForm.generalCommand;
        // }) || {};
        // this.commandForm.commandName = this.genCommInfo.methodAlias || commonString.unknown;
        // this.commandForm.commandType = this.genCommInfo.generalCommandType || commonString.unknown;
        //
      },
      protocolCommandFormSubmit() {
        this.$refs[this.protocolCommandFormRef].validate((valid) => {
          if (!valid) return;
          this.tableLoading = true;
          API.generalProtocol.generalProtocolCommandRelated(this.protocolCommandForm).then((resp) => {
            this.showCommandDialog = false;
            this.$message({
              message: "关联命令成功!",
              type: "success",
              duration: 1500,
            });
            this.genProtocolCommandData();
            this.tableLoading = false;
          }).catch((err) => {
            console.log("err: ", err);
          });

        })

      }
    },

  }
</script>


<style scoped lang="less">

</style>
